package com.agu.mgt.sys.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.agu.api.cache.map.CacheMap;
import com.agu.entity.sys.SysUserEntity;
import com.agu.mgt.sys.dao.SysOrgDao;
import com.agu.mgt.sys.dao.SysUserDao;
import com.agu.mgt.sys.dao.SysUserRoleDao;
import com.agu.mgt.sys.service.SysRoleService;
import com.agu.mgt.sys.service.SysUserRoleService;
import com.agu.mgt.sys.service.SysUserService;
import com.agu.utils.Constant;
import com.agu.utils.Query;
import com.agu.utils.RRException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 系统用户
 * 
 */
@Service("sysUserService")
@Transactional(value = "secondTransactionManager", readOnly = true)
public class SysUserService {
	@Autowired
	private SysUserDao sysUserDao;

	@Autowired
	private SysUserRoleDao sysUserRoleDao;

	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysOrgDao sysOrgDao;

	public List<String> queryAllPerms(Long userId) {
		return sysUserDao.queryAllPerms(userId);
	}

	public List<Long> queryAllMenuId(Long userId) {
		return sysUserDao.queryAllMenuId(userId);
	}

	public SysUserEntity queryByUserName(String username) {

		SysUserEntity user = sysUserDao.queryByUserName(username);

		if(user.getPlat()!=null  &&  user.getPlat().intValue() == 1)
		{
			// 全局管理员
			if (user != null && user.getUserType() == 1) {

				user.setProvinceId(0);
				user.setProvinceName("全国");
			}

			// 省级管理员
			if (user != null && user.getUserType() == 2) {

				if (user.getProvinceId() > 0) {
					user.setProvinceName(CacheMap.privinceMap.get(user.getProvinceId()));
				}
			}
		} else {
			
			Long spId = sysUserDao.getSpId(user.getUserId());
			
			user.setSpId(spId);
		}
		
		return user;
	}

	public SysUserEntity queryObject(Object userId) {
		return sysUserDao.queryObject(userId);
	}

	public List<SysUserEntity> queryList(Map<String, Object> map) {
		return sysUserDao.queryList(map);
	}

	public int queryTotal(Map<String, Object> map) {
		return sysUserDao.queryTotal(map);
	}

	@Transactional
	public void save(SysUserEntity user) {
		user.setCreateTime(new Date());
		// sha256加密
		user.setPassword(new Sha256Hash(user.getPassword()).toHex());
		sysUserDao.save(user);

		// 检查角色是否越权
		checkRole(user);

		// 保存用户与角色关系

		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Transactional
	public void update(SysUserEntity user) {

		if (StringUtils.isBlank(user.getPassword())) {
			user.setPassword(null);
		} else {
			user.setPassword(new Sha256Hash(user.getPassword()).toHex());
		}
		sysUserDao.update(user);

		// 检查角色是否越权
		checkRole(user);

		// 保存用户与角色关系
		sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
	}

	@Transactional
	public void deleteBatch(Long[] userId) {
		sysUserDao.deleteBatchUser(userId);
		sysUserDao.deleteBatchUserRole(userId);
	}

	@Transactional
	public void delete(Object userId) {
		sysUserDao.delete(userId);

		Object[] users = new Object[1];

		users[0] = userId;

		sysUserDao.deleteBatchUserRole(users);
	}

	public int updatePassword(Long userId, String password, String newPassword) {
		Map<String, Object> map = new HashMap<>();
		map.put("userId", userId);
		map.put("password", password);
		map.put("newPassword", newPassword);
		return sysUserDao.updatePassword(map);
	}

	/**
	 * 检查角色是否越权
	 */
	private void checkRole(SysUserEntity user) {
		// 如果不是超级管理员，则需要判断用户的角色是否自己创建
		if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
			return;
		}

		// 查询用户创建的角色列表
		// List<Long> roleIdList =
		// sysRoleService.queryRoleIdList(user.getCreateUserId());

		// 判断是否越权
		/*
		 * if (!roleIdList.containsAll(user.getRoleIdList())) { throw new
		 * RRException("新增用户所选角色，不是本人创建"); }
		 */
	}

	public Page<SysUserEntity> queryPageList(Query query) {
		// TODO Auto-generated method stub
		PageHelper.startPage(query.getPage(), query.getLimit());
		return sysUserDao.queryPageList(query);
	}
}
